﻿using JNPF.Basics.Models;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 菜单管理
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.09.20
    /// </summary>
    public class MenuBll
    {
        private MenuIService service = new MenuService();
        private ModuleButtonIService buttonService = new ModuleButtonService();
        private VisualDevIService visualService = new VisualDevService();
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<ModuleEntity>> GetList()
        {
            try
            {
                return await service.GetList();
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<ModuleEntity> GetInfo(string id)
        {
            try
            {
                return await service.GetInfo(id);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 重复验证（名称）
        /// </summary>
        /// <param name="fullName">名称</param>
        /// <param name="id">键值</param>
        /// <returns></returns>
        public async Task<bool> IsExistByFullName(string fullName, string id)
        {
            try
            {
                var whereLambda = ExtLinq.True<ModuleEntity>();
                whereLambda = whereLambda.And(m => m.FullName == fullName);
                if (!string.IsNullOrEmpty(id))
                    whereLambda = whereLambda.And(m => m.Id != id);
                return await service.IsExist(whereLambda);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }

        }
        /// <summary>
        /// 重复验证（编码）
        /// </summary>
        /// <param name="enCode">编码</param>
        /// <param name="id">键值</param>
        /// <returns></returns>
        public async Task<bool> IsExistByEnCode(string enCode, string id)
        {
            try
            {
                var whereLambda = ExtLinq.True<ModuleEntity>();
                whereLambda = whereLambda.And(m => m.EnCode == enCode);
                if (!string.IsNullOrEmpty(id))
                    whereLambda = whereLambda.And(m => m.Id != id);
                return await service.IsExist(whereLambda);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        public async Task Delete(ModuleEntity entity)
        {
            try
            {
                var key = CacheKey.USERAUTHORIZE + UserProvider.Instance.Get().UserId;
                if (key != null)
                {
                    CacheFactory.Cache.Remove(key);
                }
                await service.Delete(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity">实体对象</param>
        public async Task<int> Create(ModuleEntity entity)
        {
            try
            {
                entity.Id = CommonHelper.Guid;
                entity.CreatorTime = DateTime.Now;
                entity.CreatorUserId = UserProvider.Instance.Get().UserId;
                var key = CacheKey.USERAUTHORIZE + UserProvider.Instance.Get().UserId;
                if (key != null)
                {
                    CacheFactory.Cache.Remove(key);
                }
                //添加功能菜单按钮
                //if (entity.Type == 3)
                // {
                //   var propJsonMap = entity.PropertyJson.ToObject<Dictionary<string, object>>();
                //    if (propJsonMap.IsNotEmptyOrNull())
                //    {
                //        var moduleId = propJsonMap.ContainsKey("moduleId") ? propJsonMap["moduleId"].ToString() : "";
                //        var visualdevEntity = await visualService.GetInfo(moduleId);
                //        if (visualdevEntity.IsNotEmptyOrNull())
                //        {
                //            var columnDataModel = visualdevEntity.ColumnData.ToObject<ColumnDataModel>();
                //            var btnsList = columnDataModel.btnsList.Union(columnDataModel.columnBtnsList).ToList();
                //            foreach (var item in btnsList)
                //            {
                //                await buttonService.Create(new ModuleButtonEntity()
                //                {
                //                    Id = CommonHelper.Guid,
                //                    ParentId = "-1",
                //                    FullName = item.label,
                //                    EnCode = "btn_" + item.value,
                //                    SortCode = 0,
                //                    ModuleId = entity.Id,
                //                    EnabledMark = 1,
                //                    Icon = item.icon
                //                });
                //            }
                //        }
                //    }
                //}//添加字典菜单按钮
                //else 
                if (entity.Type == 4)
                {
                    var btnEntityList = (await buttonService.GetList()).FindAll(x => x.ModuleId == "-1");
                    foreach (var item in btnEntityList)
                    {
                        item.Id = CommonHelper.Guid;
                        item.ModuleId = entity.Id;
                        await buttonService.Create(item);
                    }
                }
                return await service.Create(entity);

            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }

        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="entity">实体对象</param>
        public async Task<int> Update(string id, ModuleEntity entity)
        {
            try
            {
                entity.Id = id;
                entity.LastModifyTime = DateTime.Now;
                entity.LastModifyUserId = UserProvider.Instance.Get().UserId;
                var key = CacheKey.USERAUTHORIZE + UserProvider.Instance.Get().UserId;
                if (key != null)
                {
                    CacheFactory.Cache.Remove(key);
                }
                return await service.Update(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }

        }

    }
}
